package com.holystone.orca.util.systemInfo;

import java.io.*;
import java.math.BigDecimal;

/**
 *Copyright (c) 2017, HOLYSTONE Technologies, Inc.
 * All right reserved.
 * @desc:liunx平台下 操作系统信息
 * @author qijunxing
 * @date 2017年7月17日下午5:20:40
*/
public class LiunxInfo implements SystemInfo {

	@Override
	public String DiskMessage() {
	    double totalHD = 0;
	    double usedHD = 0;
		Runtime rt = Runtime.getRuntime();
	    Process p = null;
		try {
			p = rt.exec("df -hl");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}// df -hl 查看硬盘空间
	    BufferedReader in = null;
	    try {
	    in = new BufferedReader(new InputStreamReader(p.getInputStream()));
	    String str = null;
	    String[] strArray = null;
	    while ((str = in.readLine()) != null) {
	    int m = 0;
	    strArray = str.split(" ");
	    for (String tmp : strArray) {
	    if (tmp.trim().length() == 0)
	    continue;
	    ++m;
	    if (tmp.indexOf("G") != -1) {
	    if (m == 2) {
	    if (!tmp.equals("") && !tmp.equals("0"))
	    totalHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024;
	    }
	    if (m == 3) {
	    if (!tmp.equals("none") && !tmp.equals("0"))
	    usedHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024;
	    }
	    }
	    if (tmp.indexOf("M") != -1) {
	    if (m == 2) {
	    if (!tmp.equals("") && !tmp.equals("0"))
	    totalHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1));
	    }
	    if (m == 3) {
	    if (!tmp.equals("none") && !tmp.equals("0"))
	    usedHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1));
	    }
	    }
	    }
	    }
	    } catch (Exception e) {
	   // logger.debug(e);
	    } finally {
	    try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    }
	    // 保留2位小数
	    double precent = (usedHD / totalHD) * 100;
	    BigDecimal b1 = new BigDecimal(precent);
	    precent = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	    System.out.println(precent);
	    return precent+"%";
	}

	@Override
	public String CPUMessage() {
		  float cpuUsage = 0;  
	        Process pro1,pro2;  
	        Runtime r = Runtime.getRuntime();  
	        try {  
	            String command = "cat /proc/stat";  
	            //第一次采集CPU时间  
	            long startTime = System.currentTimeMillis();  
	            pro1 = r.exec(command);  
	            BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream()));  
	            String line = null;  
	            long idleCpuTime1 = 0, totalCpuTime1 = 0;   //分别为系统启动后空闲的CPU时间和总的CPU时间  
	            while((line=in1.readLine()) != null){     
	                if(line.startsWith("cpu")){  
	                    line = line.trim();  
	                 
	                    String[] temp = line.split("\\s+");   
	                    idleCpuTime1 = Long.parseLong(temp[4]);  
	                    for(String s : temp){  
	                        if(!s.equals("cpu")){  
	                            totalCpuTime1 += Long.parseLong(s);  
	                        }  
	                    }     
	                  
	                    break;  
	                }                         
	            }     
	            in1.close();  
	            pro1.destroy();  
	            try {  
	                Thread.sleep(100);  
	            } catch (InterruptedException e) {  
	                StringWriter sw = new StringWriter();  
	                e.printStackTrace(new PrintWriter(sw));  
	            }  
	            //第二次采集CPU时间  
	            long endTime = System.currentTimeMillis();  
	            pro2 = r.exec(command);  
	            BufferedReader in2 = new BufferedReader(new InputStreamReader(pro2.getInputStream()));  
	            long idleCpuTime2 = 0, totalCpuTime2 = 0;   //分别为系统启动后空闲的CPU时间和总的CPU时间  
	            while((line=in2.readLine()) != null){     
	                if(line.startsWith("cpu")){  
	                    line = line.trim();  
	          
	                    String[] temp = line.split("\\s+");   
	                    idleCpuTime2 = Long.parseLong(temp[4]);  
	                    for(String s : temp){  
	                        if(!s.equals("cpu")){  
	                            totalCpuTime2 += Long.parseLong(s);  
	                        }  
	                    }  
	                
	                    break;    
	                }                                 
	            }  
	            if(idleCpuTime1 != 0 && totalCpuTime1 !=0 && idleCpuTime2 != 0 && totalCpuTime2 !=0){  
	                cpuUsage = 1 - (float)(idleCpuTime2 - idleCpuTime1)/(float)(totalCpuTime2 - totalCpuTime1);  
	            
	            }                 
	            in2.close();  
	            pro2.destroy();  
	        } catch (IOException e) {  
	            StringWriter sw = new StringWriter();  
	            e.printStackTrace(new PrintWriter(sw));  
	    
	        }     
	        return cpuUsage*100+"%";  
	}

	@Override
	public String MemoryMessage() {
		  float memUsage = 0.0f;  
	        Process pro = null;  
	        Runtime r = Runtime.getRuntime();  
	        try {  
	            String command = "cat /proc/meminfo";  
	            pro = r.exec(command);  
	            BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));  
	            String line = null;  
	            int count = 0;  
	            long totalMem = 0, freeMem = 0;  
	            while((line=in.readLine()) != null){      
	              //  log.info(line);   
	                String[] memInfo = line.split("\\s+");  
	                if(memInfo[0].startsWith("MemTotal")){  
	                    totalMem = Long.parseLong(memInfo[1]);  
	                }  
	                if(memInfo[0].startsWith("MemFree")){  
	                    freeMem = Long.parseLong(memInfo[1]);  
	                }  
	                memUsage = 1- (float)freeMem/(float)totalMem;  
	               // log.info("本节点内存使用率为: " + memUsage);   
	                if(++count == 2){  
	                    break;  
	                }                 
	            }  
	            in.close();  
	            pro.destroy();  
	        } catch (IOException e) {  
	            StringWriter sw = new StringWriter();  
	            e.printStackTrace(new PrintWriter(sw));  
	            //log.error("MemUsage发生InstantiationException. " + e.getMessage());  
	          //  log.error(sw.toString());  
	        }     
	        return memUsage*100+"%";  
	}
	
	public static void main(String[] args) {
		LiunxInfo w=		new LiunxInfo();
		System.out.println(w.DiskMessage());
		System.out.println(w.CPUMessage());
		System.out.println(w.MemoryMessage());
	}

}
